﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml.Linq;
using LEShortcut.Commands;
using LEShortcut.Helper;

namespace LEShortcut.Models.Views.Pages
{
    public class HomeViewModel
    {
        private readonly ICommand _allwDragCommand;
        private readonly ICommand _browseCommand;
        private readonly ICommand _saveShortcutCommand;

        public HomeViewModel()
        {
            Context = new HomeViewContext();
            _browseCommand = new BrowseShortcutCommand();
            _saveShortcutCommand = new SaveShortcutCommand();
            _allwDragCommand = new AllowDragCommand();
            Init();
        }

        public HomeViewContext Context { get; private set; }

        public ICommand SaveShortcutCommand
        {
            get { return _saveShortcutCommand; }
        }

        public ICommand AllwDragCommand
        {
            get { return _allwDragCommand; }
        }

        public ICommand BrowseCommand
        {
            get { return _browseCommand; }
        }

        private void Init()
        {
            var cache = Application.Current.Resources["cache"] as AppCache;
            Debug.Assert(cache != null, "cache != null");
            Context.Config = cache.Config;
            if (cache.LeConfig != null && cache.LeConfig.Any()) Context.LeConfig = cache.LeConfig;
            else
            {
                Context.LeConfig =
                    XDocument.Load(Path.Combine(Context.Config.LePath, "LEConfig.xml"))
                        .Elements("LEConfig")
                        .First()
                        .Elements("Profiles")
                        .First()
                        .Elements("Profile").ToList();
                cache.LeConfig = Context.LeConfig;
            }
        }

        public void DragDropCommand(object obj, DragEventArgs e)
        {
            string[] paths = PathHelper.ValidatedExtractor((string[]) e.Data.GetData(DataFormats.FileDrop));
            CommandHelper.ParserShortcuts(paths, Context);
        }

        public void ProfileSelectionChanged(object obj, EventArgs e)
        {
            var control = obj as ComboBox;
            if (control != null) Context.ChoosedProfile = (string) control.SelectedValue;
        }
    }
}